const Service = require('egg').Service;

class ConversationService extends Service {
  // 创建或获取会话
  async createOrGetConversation(userId, targetUserId) {
    const { ctx } = this;
    
    // 确保userId小于targetUserId，避免重复创建会话
    const [user1Id, user2Id] = userId < targetUserId 
      ? [userId, targetUserId] 
      : [targetUserId, userId];
      
    // 查找现有会话
    let conversation = await ctx.model.Conversation.findOne({
      where: {
        user1_id: user1Id,
        user2_id: user2Id,
        is_active: 1
      }
    });
    
    // 如果不存在则创建新会话
    if (!conversation) {
      conversation = await ctx.model.Conversation.create({
        user1_id: user1Id,
        user2_id: user2Id,
        is_active: 1,
        created_at: new Date(),
        updated_at: new Date()
      });
    }
    
    return conversation;
  }
  
  // 获取用户的会话列表
  async getUserConversations(userId, query) {
    const { ctx } = this;
    const { page = 1, pageSize = 20 } = query;
    
    const options = {
      where: {
        [ctx.app.Sequelize.Op.or]: [
          { user1_id: userId },
          { user2_id: userId }
        ],
        is_active: 1
      },
      limit: parseInt(pageSize),
      offset: (parseInt(page) - 1) * parseInt(pageSize),
      order: [['last_message_at', 'DESC']]
    };
    
    const { count, rows } = await ctx.model.Conversation.findAndCountAll(options);
    
    // 获取每个会话的对方用户信息和最后一条消息
    const conversations = await Promise.all(rows.map(async conv => {
      // 确定对方用户ID
      const otherUserId = conv.user1_id === userId ? conv.user2_id : conv.user1_id;
      
      // 获取对方用户信息
      const otherUser = await ctx.model.User.findByPk(otherUserId, {
        attributes: ['user_id', 'nickname', 'avatar']
      });
      
      // 获取最后一条消息
      let lastMessage = null;
      if (conv.last_message_id) {
        lastMessage = await ctx.model.Message.findByPk(conv.last_message_id);
      }
      
      return {
        ...conv.toJSON(),
        other_user: otherUser,
        last_message: lastMessage
      };
    }));
    
    return {
      list: conversations,
      pagination: {
        page: parseInt(page),
        pageSize: parseInt(pageSize),
        total: count,
        totalPages: Math.ceil(count / pageSize)
      }
    };
  }
  
  // 获取会话详情
  async getConversationDetail(conversationId, userId) {
    const { ctx } = this;
    
    const conversation = await ctx.model.Conversation.findOne({
      where: {
        id: conversationId,
        [ctx.app.Sequelize.Op.or]: [
          { user1_id: userId },
          { user2_id: userId }
        ],
        is_active: 1
      }
    });
    
    if (!conversation) {
      throw new Error('会话不存在或已关闭');
    }
    
    // 获取对方用户信息
    const otherUserId = conversation.user1_id === userId ? conversation.user2_id : conversation.user1_id;
    const otherUser = await ctx.model.User.findByPk(otherUserId, {
      attributes: ['user_id', 'nickname', 'avatar']
    });
    
    return {
      ...conversation.toJSON(),
      other_user: otherUser
    };
  }
  
  // 关闭会话
  async closeConversation(conversationId, userId) {
    const { ctx } = this;
    
    const conversation = await ctx.model.Conversation.findOne({
      where: {
        id: conversationId,
        [ctx.app.Sequelize.Op.or]: [
          { user1_id: userId },
          { user2_id: userId }
        ]
      }
    });
    
    if (!conversation) {
      throw new Error('会话不存在');
    }
    
    await conversation.update({
      is_active: 0,
      updated_at: new Date()
    });
    
    return true;
  }
  
  // 更新会话的最后一条消息
  async updateLastMessage(conversationId, messageId) {
    const { ctx } = this;
    
    const conversation = await ctx.model.Conversation.findByPk(conversationId);
    if (!conversation) {
      throw new Error('会话不存在');
    }
    
    // 获取消息详情
    const message = await ctx.model.Message.findByPk(messageId);
    if (!message) {
      throw new Error('消息不存在');
    }
    
    // 更新未读计数（如果不是自己发送的消息）
    const updateData = {
      last_message_id: messageId,
      last_message_at: message.created_at,
      updated_at: new Date()
    };
    
    // 如果消息接收者是会话中的一方，增加未读计数
    if (conversation.user1_id !== message.sender_id) {
      updateData.unread_count = ctx.app.Sequelize.literal('unread_count + 1');
    } else if (conversation.user2_id !== message.sender_id) {
      updateData.unread_count = ctx.app.Sequelize.literal('unread_count + 1');
    }
    
    await conversation.update(updateData);
    return conversation;
  }
  
  // 重置未读计数
  async resetUnreadCount(conversationId, userId) {
    const { ctx } = this;
    
    const conversation = await ctx.model.Conversation.findOne({
      where: {
        id: conversationId,
        [ctx.app.Sequelize.Op.or]: [
          { user1_id: userId },
          { user2_id: userId }
        ]
      }
    });
    
    if (!conversation) {
      throw new Error('会话不存在');
    }
    
    await conversation.update({
      unread_count: 0,
      updated_at: new Date()
    });
    
    return conversation;
  }
}

module.exports = ConversationService;